/**
 *
 */
package com.printeverywhere.job;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.Type;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.opensymphony.xwork2.ActionContext;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.dto.AuctionInvoices;
import com.printeverywhere.dto.AuctionWonlist;
import com.printeverywhere.dto.MailingSystem;
import com.printeverywhere.dto.Transactions;
import com.printeverywhere.dto.TransactionsUser;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.MailHelper;

/**
 * @author punam
 *
 */
public class ProcessGenerateInvoicesJob implements Job, ServletRequestAware{

	private static Logger logger = Logger.getLogger(ProcessGenerateInvoicesJob.class);

	private List<Criterion> criterionList = new ArrayList<Criterion>();

	private List<AuctionInvoices> invoicesList = new ArrayList<AuctionInvoices>();

	private List<Transactions> transactionsList = new ArrayList<Transactions>();

	private List<TransactionsUser> transactionsUserList = new ArrayList<TransactionsUser>();

	private HttpServletRequest request;

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		try{
			transactionsUserList = (List<TransactionsUser>) CommonFunctionDelegator.getAllfromtable(TransactionsUser.class.getName());
			for (Iterator iterator = transactionsUserList.iterator(); iterator.hasNext();) {
				TransactionsUser type = (TransactionsUser) iterator.next();
				if(criterionList.size() > 0){
					criterionList.clear();
				}
				criterionList.add(Restrictions.eq("invoice", null));
				criterionList.add(Restrictions.eq("user", type.getUserId()));
				transactionsList = (List<Transactions>) CommonFunctionDelegator.getObjectsByCriterion(criterionList, null, null, Transactions.class);
				double amount = 0.0;
				if(transactionsList.size() > 0){
					/* Generate invoices for auctionWinners. */
					MailingSystem mailingSystem = (MailingSystem) CommonFunctionDelegator.getAllfromtable(MailingSystem.class.getName()).get(AdminConstants.ZERO_NUMBER);
					MailHelper mailHelper = new MailHelper(mailingSystem.getServerAddress(), mailingSystem.getServerUsername(), mailingSystem.getServerPassword());
					StringBuffer URL = new StringBuffer();
					URL.append(CommonUtil.getLocalBasePath(request));
					URL.append("/mail/auctionWonMail.htm?username=").append(type.getUserId().getUserId()).append("&data=").append("<table width=\"100%\">");
					URL.append("<tr>");
					URL.append("<td>");
					URL.append("Item Nr.");
					URL.append("</td>");
					URL.append("<td>");
					URL.append("Item Qty");
					URL.append("</td>");
					URL.append("<td>");
					URL.append("Item Price");
					URL.append("</td>");
					URL.append("<td>");
					URL.append("Total");
					URL.append("</td>");
					URL.append("</tr>");
					for (Iterator transactionsIterator = transactionsList.iterator(); transactionsIterator
							.hasNext();) {
						Transactions transactions = (Transactions) transactionsIterator.next();
						if (transactions.getUser() != null
								&& transactions.getId() != null) {
							if (criterionList.size() > 0) {
								criterionList.clear();
							}
							criterionList.add(Restrictions.eq("user",
									transactions.getUser()));
							criterionList.add(Restrictions.eq("items",
									transactions.getId()));
							if(CommonFunctionDelegator.getObjectsByCriterion(criterionList, null, null, AuctionWonlist.class).size() > 0){
								AuctionWonlist auctionWonlist = (AuctionWonlist) CommonFunctionDelegator
										.getObjectsByCriterion(criterionList, null,
												null, AuctionWonlist.class).get(
														AdminConstants.ZERO_NUMBER);
								URL.append("<tr>");
								URL.append("<td>");
								URL.append(auctionWonlist.getItems()
										.getItemId());
								URL.append("</td>");
								URL.append("<td>");
								URL.append(auctionWonlist.getQuantity());
								URL.append("</td>");
								URL.append("<td>");
								URL.append(auctionWonlist.getPrice());
								URL.append("</td>");
								URL.append("<td>");
								URL.append(auctionWonlist.getQuantity()
										* auctionWonlist.getPrice());
								URL.append("</td>");
								URL.append("</tr>");
								amount = amount
										+ (auctionWonlist.getQuantity() * auctionWonlist
												.getPrice());
								logger.info("Auction won invoice sent.");
							}
						}
					}
					URL.append("<tr>");
					URL.append("<td colspan=\"3\">");
					URL.append("Total Amount: ");
					URL.append("</td>");
					URL.append("<td>");
					URL.append(amount);
					URL.append("</td>");
					URL.append("</tr>");
					URL.append("</table>");
					String message = CommonUtil.getURLContent(URL.toString());
					mailHelper.sendMail(mailingSystem.getAccountsConfirmationEmail(), type.getUserId().getEmail(), "Invoice for auctions won.", message);
					System.out.println("URL Content:: "+ URL.toString());
				}
			}
		}catch (Exception e) {

		}
	}

	public static void main(String[] args) {
		/*try{

			transactionsUserList = (List<TransactionsUser>) CommonFunctionDelegator.getAllfromtable(TransactionsUser.class.getName());
			List<Criterion> criterionList = new ArrayList<Criterion>();
			for (Iterator iterator = transactionsUserList.iterator(); iterator.hasNext();) {
				TransactionsUser type = (TransactionsUser) iterator.next();
				if(criterionList.size() > 0){
					criterionList.clear();
				}
				criterionList.add(Restrictions.isNull("invoice"));
				criterionList.add(Restrictions.eq("user", type.getUserId()));
				List<Transactions> transactionsList = new ArrayList<Transactions>();
				transactionsList = (List<Transactions>) CommonFunctionDelegator.getObjectsByCriterion(criterionList, null, null, Transactions.class);
				double amount = 0.0;
				if(transactionsList.size() > 0){
					 Generate invoices for auctionWinners.
					MailingSystem mailingSystem = (MailingSystem) CommonFunctionDelegator.getAllfromtable(MailingSystem.class.getName()).get(AdminConstants.ZERO_NUMBER);
					MailHelper mailHelper = new MailHelper(mailingSystem.getServerAddress(), mailingSystem.getServerUsername(), mailingSystem.getServerPassword());
					StringBuffer URL = new StringBuffer();
//					URL.append(CommonUtil.getLocalBasePath(request));
					URL.append("/mail/auctionWonMail.htm?username=").append(type.getUserId().getUserId()).append("&data=").append("<table width=\"100%\">");
					URL.append("<tr>");
					URL.append("<td>");
					URL.append("Item Nr.");
					URL.append("</td>");
					URL.append("<td>");
					URL.append("Item Qty");
					URL.append("</td>");
					URL.append("<td>");
					URL.append("Item Price");
					URL.append("</td>");
					URL.append("<td>");
					URL.append("Total");
					URL.append("</td>");
					URL.append("</tr>");
					for (Iterator transactionsIterator = transactionsList.iterator(); transactionsIterator
							.hasNext();) {
						Transactions transactions = (Transactions) transactionsIterator.next();
						if(criterionList.size() > 0){
							criterionList.clear();
						}
						if(transactions.getUser() != null && transactions.getId() != null){
							criterionList.add(Restrictions.eq("user", transactions.getUser()));
							criterionList.add(Restrictions.eq("items", transactions.getId()));
							if(CommonFunctionDelegator.getObjectsByCriterion(criterionList, null, null, AuctionWonlist.class).size() > 0){
								AuctionWonlist auctionWonlist = (AuctionWonlist) CommonFunctionDelegator.getObjectsByCriterion(criterionList, null, null, AuctionWonlist.class).get(AdminConstants.ZERO_NUMBER);
								URL.append("<tr>");
								URL.append("<td>");
								URL.append(auctionWonlist.getItems().getItemId());
								URL.append("</td>");
								URL.append("<td>");
								URL.append(auctionWonlist.getQuantity());
								URL.append("</td>");
								URL.append("<td>");
								URL.append(auctionWonlist.getPrice());
								URL.append("</td>");
								URL.append("<td>");
								URL.append(auctionWonlist.getQuantity() * auctionWonlist.getPrice());
								URL.append("</td>");
								URL.append("</tr>");
								amount = amount + (auctionWonlist.getQuantity() * auctionWonlist.getPrice());
								logger.info("Auction won invoice sent.");
							}
						}
					}
					URL.append("<tr>");
					URL.append("<td colspan=\"3\">");
					URL.append("Total Amount: ");
					URL.append("</td>");
					URL.append("<td>");
					URL.append(amount);
					URL.append("</td>");
					URL.append("</tr>");
					URL.append("</table>");
					String message = CommonUtil.getURLContent(URL.toString());
//					mailHelper.sendMail(mailingSystem.getAccountsConfirmationEmail(), type.getUserId().getEmail(), "Invoice for auctions won.", message);
					System.out.println("URL Content:: "+ URL.toString());
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}*/
	}

	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
	}

}
